package org.tinygroup.channel.protocol.impl;

import java.util.ArrayList;
import java.util.List;

import org.tinygroup.channel.protocol.ProtocolOutInterface;
import org.tinygroup.channel.protocol.ProtocolOutListener;
import org.tinygroup.context.Context;

@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class AbstractProtocolOut<ProRequest, ProResponse> extends
		AbstractProtocol implements
		ProtocolOutInterface<ProRequest, ProResponse> {
	private List<ProtocolOutListener> listeners = new ArrayList<ProtocolOutListener>();

	public List<ProtocolOutListener> getListeners() {
		return listeners;
	}

	public void setListeners(List<ProtocolOutListener> listeners) {
		this.listeners = listeners;
	}

	public void addProtocolListener(ProtocolOutListener listener) {
		listeners.add(listener);
	}

	protected Object beforeSend(Object bizRequest, Context context) {
		for (ProtocolOutListener listener : listeners) {
			bizRequest = listener.beforeSend(bizRequest, context);
		}
		return bizRequest;
	}

	protected ProRequest afterBizToRequestTrans(Object bizRequest,
			ProRequest request, Context context) {
		for (ProtocolOutListener listener : listeners) {
			request = (ProRequest) listener.afterBizToRequestTrans(bizRequest,
					request, context);
		}
		return request;
	}

	protected ProResponse afterSend(ProRequest proRequest,
			ProResponse proResponse, Context context) {
		for (ProtocolOutListener listener : listeners) {
			proResponse = (ProResponse) listener.afterSend(proRequest,
					proResponse, context);
		}
		return proResponse;
	}

	protected Object afterResponseToBizTrans(ProResponse proResponse,
			Object bizResponse, Context context) {
		for (ProtocolOutListener listener : listeners) {
			bizResponse = listener.afterResponseToBizTrans(proResponse,
					bizResponse, context);
		}
		return bizResponse;
	}
}
